<?php

namespace app\admin\controller\deerhome;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 优惠券
 *
 * @icon fa fa-circle-o
 */
class Yhq extends Backend
{

    /**
     * Yhq模型对象
     * @var \app\admin\model\deerhome\Yhq
     */
    protected $model = null;
    protected $searchFields = 'name';
    protected $relationSearch = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\deerhome\Yhq;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    public function setPass(){
        $this->model->where("status","in",[1,2])->where('end_day',"<",date('Y-m-d'))->update(['status'=>4]);
    }
    public function index()
    {
        if (!$this->request->isAjax())
        {
            $this->setPass();
            return $this->view->fetch();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model
                ->with(["user"])
                ->where($where)
                ->count();
        $list = $this->model
                ->with(["user"])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

        $adminIds = $this->getDataLimitAdminIds();
        $cate=db('deerhome_cate')->field('id,name')->where('cate_id',0)->column('name','id');
        foreach($list as $k=>&$v){
            if($v['status']==1){
                $v['code']=\substr($v['code'],0,4)."****".\substr($v['code'],-4);
            }
            if($v['jz_cate_ids']=='0'){
                $v['cate_name']="全品类";
                continue;
            }
            $jz_cate_ids=explode(',',$v['jz_cate_ids']);
            $jz_cate_ids=array_filter($jz_cate_ids);
            $cate_name=[];
            foreach($jz_cate_ids as $k1=>$v1){
                if(!isset($cate[$v1])){
                    continue;
                }
                $cate_name[]=$cate[$v1];
            }
            $v['cate_name']=implode(',',$cate_name);
        }
        $result = array("total" => $total, "rows" => $list);
        return json($result);
    }
   /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        $adminIds = $this->getDataLimitAdminIds();
        if (false === $this->request->isPost()) {
            $list=db('deerhome_cate')->field('id,name')->where('cate_id',0)->where('status',1)->column('name','id');
            $this->assign("cateData", $list);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['nums']=intval($params['nums']);
        $params['jz_cate_ids']=$this->request->post("jz_cate_ids/a");
        $params['jz_cate_ids']=array_filter($params['jz_cate_ids']);
        if(count($params['jz_cate_ids'])==0){
            $params['jz_cate_ids']='0';
        }else{
            $params['jz_cate_ids']='0,'.implode(',',$params['jz_cate_ids']).',0';
        }

        if($params['nums']<=0){
            $this->error("数量必须大于0");
        }
        if(\bccomp($params['money_lev'],$params['money_yh'],2)<0){
            $this->error("减免金额不能超过满减金额");
        }
        if(\bccomp($params['money_lev'],0,2)<=0){
            $this->error("满减金额必须大于0");
        }
        if(\bccomp($params['money_yh'],0,2)<=0){
            $this->error("优惠金额必须大于0");
        }
        if(!preg_match("/^2\d{3}-\d{2}-\d{2}$/",$params['start_day'])){
            $this->error("开始时间格式不正确");
        }
        if(!preg_match("/^2\d{3}-\d{2}-\d{2}$/",$params['end_day'])){
            $this->error("结束时间格式不正确");
        }
        if(strtotime($params['start_day'])>strtotime($params['end_day'])){
            $this->error("开始时间不能大于结束时间");
        }
        $params['addtime']=\date("Y-m-d H:i:s");
        $code=$this->generateCode($params['nums']);
        $addArr=[];
        foreach($code as $k=>$v){
            $addArr[]=[
                'name'=>$params['name'],
                'money_lev'=>$params['money_lev'],
                'money_yh'=>$params['money_yh'],
                'start_day'=>$params['start_day'],
                'end_day'=>$params['end_day'],
                'jz_cate_ids'=>$params['jz_cate_ids'],
                'code'=>$v,
                'addtime'=>$params['addtime']
            ];
        }
        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->allowField(true)->saveAll($addArr);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
/**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $list=db('deerhome_cate')->field('id,name')->where('cate_id',0)->where('status',1)->column('name','id');
            $this->assign("cateData", $list);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        parent::edit($ids);
    }
    /**
     * 生成优惠码
     * @param int $nums             生成多少个优惠码
     * @param array $exist_array     排除指定数组中的优惠码
     * @param int $code_length         生成优惠码的长度
     * @param int $prefix              生成指定前缀
     * @return array                 返回优惠码数组
     */
    private function generateCode( $nums,$exist_array='',$code_length = 12,$prefix = '' ) {
    
        $characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz";
        $promotion_codes = array();//这个数组用来接收生成的优惠码
        for($j = 0 ; $j < $nums; $j++) {
            $code = '';
            for ($i = 0; $i < $code_length; $i++) {
    
                $code .= $characters[mt_rand(0, strlen($characters)-1)];
            }
            //如果生成的4位随机数不再我们定义的$promotion_codes数组里面
            if( !in_array($code,$promotion_codes) ) {
                if( is_array($exist_array) ) {
                    if( !in_array($code,$exist_array) ) {//排除已经使用的优惠码
                        $promotion_codes[$j] = $prefix.$code; //将生成的新优惠码赋值给promotion_codes数组
                    } else {
                        $j--;
                    }
                } else {
                    $promotion_codes[$j] = $prefix.$code;//将优惠码赋值给数组
                }
            } else {
                $j--;
            }
        }
        return $promotion_codes;
    }
}
